package com.slfx.open.api.handle;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.slfx.open.api.sdk.common.exception.CommonException;
import com.slfx.open.api.sdk.common.exception.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;


@Component
@Slf4j
public class RestTemplateHandle {

    @Resource(name = "faceRestTemplate")
    private RestTemplate restTemplate;


    /**
     * get请求
     * @param requestUrl
     * @param headerMap
     * @param paramJson
     * @param resp
     * @return
     * @throws RuntimeException
     */
    public Object getObject(String requestUrl, Map<String, String> headerMap, String paramJson, Class<?> resp) throws RuntimeException {
        HttpHeaders httpHeaders = new HttpHeaders();
        if (CollUtil.isNotEmpty(headerMap)) {
            for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) {
                httpHeaders.set(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        String url = "";
        if (StringUtils.isNotEmpty(paramJson)) {
            Map dataValue = JSONUtil.toBean(paramJson, Map.class);

            Iterator<Map.Entry<String, Object>> iterator = dataValue.entrySet().iterator();
            StringBuffer sb = new StringBuffer();
            sb.append("?");
            while (iterator.hasNext()) {
                Map.Entry<String, Object> e = iterator.next();
                String key = e.getKey();
                String value = e.getValue() == null ? "" : e.getValue().toString();
                sb.append(key + "=").append(value).append("&");
            }
            url = sb.toString();
            url = url.substring(0, url.length() - 1);
        }
        url = requestUrl + url;
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity<?> result = null;
        try {
            result = restTemplate.exchange(url, HttpMethod.GET, httpEntity, resp);
            if (result.getStatusCode() != HttpStatus.OK) {
                throw new CommonException(ErrorCodeEnum.ERROR_APP_ERR);
            }
        } catch (RestClientException e) {
            log.error("getObject error e{}", e);
            throw new CommonException(ErrorCodeEnum.ERROR_APP_ERR);
        }
        return result.getBody();
    }

    /**
     * post 请求
     *
     * @param url       请求地址
     * @param headerMap 头信息
     * @return JSONObject
     */
    public Object postToJson(String url, Map<String, String> headerMap, String paramJson, Class<?> resp) throws CommonException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        if (CollUtil.isNotEmpty(headerMap)) {
            for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) {
                httpHeaders.set(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        HttpEntity httpEntity = new HttpEntity(paramJson, httpHeaders);
        ResponseEntity<?> responseEntity = restTemplate.postForEntity(url, httpEntity, resp);
        Object  body = responseEntity.getBody();
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new CommonException(ErrorCodeEnum.ERROR_APP_ERR);
        }
        return body;
    }

    /**
     * post 请求
     *
     * @param url       请求地址
     * @param headerMap 头信息
     * @return JSONObject
     */
    public Object postToForm(String url, Map<String, String> headerMap, MultiValueMap<String, Object> dataValue, Class<?> resp) throws CommonException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if (CollUtil.isNotEmpty(headerMap)) {
            for (Map.Entry<String, String> stringStringEntry : headerMap.entrySet()) {
                httpHeaders.set(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        HttpEntity httpEntity = new HttpEntity(dataValue, httpHeaders);
        Object body = null;
        try {
            ResponseEntity<?> responseEntity = restTemplate.postForEntity(url, httpEntity, resp);
            body = responseEntity.getBody();
            if (responseEntity.getStatusCode() != HttpStatus.OK) {
                throw new CommonException(ErrorCodeEnum.ERROR_APP_ERR);
            }
        } catch (Exception e) {
            log.error("postObject error e{}", e);
            throw new CommonException(ErrorCodeEnum.ERROR_APP_ERR);
        }

        return body;
    }
}
